﻿using System;
using EPiServer.Cms.Shell.UI.ObjectEditing.EditorDescriptors;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Shell.ObjectEditing.EditorDescriptors;
using System.Linq;

namespace OpenWaves.EPiServer.ExtendedContentAreaEditor
{
    [EditorDescriptorRegistration(TargetType = typeof (ContentArea), UIHint = UIHint)]
    public class ExtendedContentAreaEditorDescriptor : ContentAreaEditorDescriptor
    {
        public const string UIHint = "ExtendedContentArea";

        public ExtendedContentAreaEditorDescriptor()
        {
            this.ClientEditingClass = "ow.epi.extendedContentAreaEditor.formEditingWidget";
        }

        public override void ModifyMetadata(global::EPiServer.Shell.ObjectEditing.ExtendedMetadata metadata,
                                            System.Collections.Generic.IEnumerable<Attribute> attributes)
        {
            base.ModifyMetadata(metadata, attributes);

            metadata.CustomEditorSettings["overlayType"] = "ow.epi.extendedContentAreaEditor.overlayBlockArea";

            var contentAreaSupportedTypesAttribute =
                attributes.OfType<ContentAreaSupportedTypesAttribute>().SingleOrDefault();
            if (contentAreaSupportedTypesAttribute == null)
            {
                throw new ApplicationException("ContentAreaSupportedTypesAttribute not found");
            }

            var contentTypeRepository =
                global::EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
            
            var supportedTypes = contentAreaSupportedTypesAttribute.SupportedTypes.Select(ca =>
                {
                    var contentType = contentTypeRepository.Load(ca);
                    return new
                        {
                            contentType.ID, Name = contentType.LocalizedName
                        };
                });

            metadata.OverlayConfiguration.Add("SupportedTypes", supportedTypes);
            metadata.EditorConfiguration.Add("SupportedTypes", supportedTypes);
        }
    }
}